<template>
  <el-dialog
    v-model="visible"
    title="余额充值"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="recharge-dialog">
      <!-- 当前余额 -->
      <div class="current-balance">
        <span>当前余额：</span>
        <span class="balance-amount">¥{{ currentBalance }}</span>
      </div>

      <!-- 充值金额选择 -->
      <div class="recharge-amounts">
        <h4>选择充值金额</h4>
        <div class="amount-grid">
          <div
            v-for="amount in presetAmounts"
            :key="amount"
            class="amount-item"
            :class="{ active: selectedAmount === amount }"
            @click="selectAmount(amount)"
          >
            ¥{{ amount }}
          </div>
        </div>
        <div class="custom-amount">
          <el-input
            v-model.number="customAmount"
            placeholder="自定义金额"
            :min="1"
            type="number"
            @input="onCustomAmountInput"
          >
            <template #prepend>¥</template>
          </el-input>
        </div>
      </div>

      <!-- 充值说明 -->
      <div class="recharge-info" v-if="balanceConfig">
        <el-alert
          :title="balanceConfig.recharge_tips"
          type="info"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 支付方式 -->
      <div class="payment-method">
        <h4>支付方式</h4>
        <el-radio v-model="paymentMethod" label="yipay" disabled>
          易支付 (推荐)
        </el-radio>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleRecharge"
          :loading="loading"
          :disabled="!selectedAmount"
        >
          立即充值
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 支付二维码对话框 -->
  <el-dialog
    v-model="paymentVisible"
    title="扫码支付"
    width="400px"
    :close-on-click-modal="false"
    @close="handlePaymentClose"
  >
    <div class="payment-dialog">
      <div class="payment-amount">
        <p>充值金额：<span class="amount">¥{{ finalAmount }}</span></p>
      </div>
      <div class="payment-qr" v-if="paymentData">
        <img :src="paymentData.qr_code" alt="支付二维码" />
        <p class="qr-tip">请使用微信或支付宝扫码支付</p>
      </div>
      <div class="payment-order">
        <p>订单号：{{ paymentData?.order_no }}</p>
      </div>
      <div class="payment-status">
        <el-button type="primary" @click="checkPaymentStatus" :loading="checkingStatus">
          支付完成
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createRechargeOrder, getBalanceConfig } from '@/api/balance'

export default {
  name: 'BalanceRechargeDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    currentBalance: {
      type: Number,
      default: 0
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const state = reactive({
      visible: false,
      loading: false,
      paymentVisible: false,
      checkingStatus: false,
      selectedAmount: null,
      customAmount: '',
      paymentMethod: 'yipay',
      presetAmounts: [50, 100, 200, 500, 1000, 2000],
      balanceConfig: null,
      paymentData: null,
      finalAmount: 0
    })

    // 监听对话框显示状态
    const unwatch = ref(null)
    unwatch.value = () => {
      state.visible = props.modelValue
    }

    // 选择金额
    const selectAmount = (amount) => {
      state.selectedAmount = amount
      state.customAmount = ''
    }

    // 自定义金额输入
    const onCustomAmountInput = () => {
      if (state.customAmount) {
        state.selectedAmount = state.customAmount
      }
    }

    // 获取余额配置
    const loadBalanceConfig = async () => {
      try {
        const response = await getBalanceConfig()
        if (response.data.code === 200) {
          state.balanceConfig = response.data.data
        }
      } catch (error) {
        console.error('获取余额配置失败:', error)
      }
    }

    // 处理充值
    const handleRecharge = async () => {
      if (!state.selectedAmount || state.selectedAmount <= 0) {
        ElMessage.warning('请选择充值金额')
        return
      }

      state.loading = true
      try {
        const response = await createRechargeOrder(state.selectedAmount)
        if (response.data.code === 200) {
          state.paymentData = response.data.data
          state.finalAmount = state.selectedAmount
          state.paymentVisible = true
          ElMessage.success('订单创建成功，请完成支付')
        } else {
          ElMessage.error(response.data.message || '创建订单失败')
        }
      } catch (error) {
        console.error('创建充值订单失败:', error)
        ElMessage.error('创建充值订单失败')
      } finally {
        state.loading = false
      }
    }

    // 检查支付状态
    const checkPaymentStatus = async () => {
      state.checkingStatus = true
      try {
        // 这里可以调用检查支付状态的API
        // 暂时直接模拟支付成功
        setTimeout(() => {
          state.checkingStatus = false
          state.paymentVisible = false
          handleClose()
          emit('success')
          ElMessage.success('充值成功！')
        }, 1000)
      } catch (error) {
        state.checkingStatus = false
        ElMessage.error('检查支付状态失败')
      }
    }

    // 关闭对话框
    const handleClose = () => {
      state.visible = false
      state.selectedAmount = null
      state.customAmount = ''
      state.paymentData = null
      emit('update:modelValue', false)
    }

    // 关闭支付对话框
    const handlePaymentClose = () => {
      state.paymentVisible = false
      state.paymentData = null
    }

    onMounted(() => {
      loadBalanceConfig()
    })

    return {
      ...toRefs(state),
      selectAmount,
      onCustomAmountInput,
      handleRecharge,
      checkPaymentStatus,
      handleClose,
      handlePaymentClose
    }
  }
}
</script>

<style scoped>
.recharge-dialog {
  padding: 20px 0;
}

.current-balance {
  text-align: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.balance-amount {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-left: 8px;
}

.recharge-amounts h4 {
  margin-bottom: 16px;
  color: #303133;
}

.amount-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 16px;
}

.amount-item {
  padding: 16px;
  text-align: center;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.amount-item:hover {
  border-color: #409eff;
  color: #409eff;
}

.amount-item.active {
  border-color: #409eff;
  background: #ecf5ff;
  color: #409eff;
}

.custom-amount {
  margin-top: 16px;
}

.recharge-info {
  margin: 24px 0;
}

.payment-method h4 {
  margin-bottom: 12px;
  color: #303133;
}

.payment-dialog {
  text-align: center;
  padding: 20px 0;
}

.payment-amount {
  margin-bottom: 24px;
  font-size: 16px;
}

.payment-amount .amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.payment-qr {
  margin: 24px 0;
}

.payment-qr img {
  width: 200px;
  height: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.qr-tip {
  margin-top: 12px;
  color: #909399;
  font-size: 14px;
}

.payment-order {
  margin: 16px 0;
  color: #606266;
  font-size: 14px;
}

.payment-status {
  margin-top: 24px;
}
</style>